package com.example.music08.fragment;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.NotificationTarget;
import com.example.music08.MainActivity;
import com.example.music08.MainActivity2;
import com.example.music08.R;
import com.example.music08.adapter.MusicAdapter;
import com.example.music08.entity.Music;
import com.example.music08.utils.HttpUtils;
import com.example.music08.utils.MusicUtils;
import com.example.music08.utils.SqlUtils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

public class BlankFragment extends Fragment {


    private EditText et;
    private ListView lvNet;

    List<Music.DataBean> list = new ArrayList<>();
    MusicAdapter musicAdapter;
    private ImageView ivNet;
    private TextView nameNet;
    private ImageView preNet;
    private ImageView pOrpNet;
    private ImageView nextNet;
    MyReceiver myReceiver;

    public BlankFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View inflate = inflater.inflate(R.layout.fragment_blank, container, false);
        initView(inflate);

        myReceiver = new MyReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.bw.pre");
        intentFilter.addAction("com.bw.pOrp");
        intentFilter.addAction("com.bw.next");
        intentFilter.addAction("com.bw.pre.main2");
        intentFilter.addAction("com.bw.pOrp.main2");
        intentFilter.addAction("com.bw.next.main2");
        getActivity().registerReceiver(myReceiver,intentFilter);

        musicAdapter = new MusicAdapter(list);
        lvNet.setAdapter(musicAdapter);

        new MyTask().execute("http://10.161.9.80:7004/song/json?singer=%E9%82%93%E7%B4%AB%E6%A3%8B");

        //查询功能 --可根据歌曲名称实现模糊查询
        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //获取editText输入的文本
                String string = et.getText().toString();
                List<Music.DataBean> newlist = new ArrayList<>();//用来存放符合条件的数据
                if (string.isEmpty()) {//写完文字，在删除文字
                    new MyTask().execute("http://10.161.9.80:7004/song/json?singer=%E9%82%93%E7%B4%AB%E6%A3%8B");
                } else {
                    //循环所有数据，判断歌曲名称是否保存 et，如果保存，存放到newlist
                    for (Music.DataBean bean : list) {
                        if (bean.getName().contains(string)) {
                            newlist.add(bean);
                        }
                    }
                    //展示页面上
                    list.clear();
                    list.addAll(newlist);
                    musicAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        //点击能够放歌，同时跳转到详情界面
        lvNet.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                MusicUtils.getInstance().play(position);
                //startActivity(new Intent(getActivity(), MainActivity2.class));
                //发送通知，---下方内容变化
                sendNoti(1);
                change();
            }
        });
        lvNet.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                SqlUtils.getInstance(getActivity()).insert(list.get(position), "sc");
                Toast.makeText(getActivity(), "收藏成功", Toast.LENGTH_SHORT).show();
                return true;
            }
        });
        //下方图片点击事件
        preNet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicUtils.getInstance().pre();
                sendNoti(1);
                change();
            }
        });
        nextNet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicUtils.getInstance().next();
                sendNoti(1);
                change();
            }
        });
        pOrpNet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MusicUtils.getInstance().pOrp(pOrpNet);
                sendNoti(2);
            }
        });
        //跳转到详情界面
        ivNet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(),MainActivity2.class));
            }
        });

        return inflate;
    }

    private void change() {
        nameNet.setText(MusicUtils.getInstance().getName());
        Glide.with(getActivity()).load(MusicUtils.getInstance().getPicUrl()).into(ivNet);
        pOrpNet.setImageResource(R.drawable.baseline_pause_circle_outline_24);
    }

    @SuppressLint("RemoteViewLayout")
    private void sendNoti(int type) {
        NotificationManager manager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
        RemoteViews remoteViews = new RemoteViews(getActivity().getPackageName(), R.layout.noti);
        remoteViews.setTextViewText(R.id.name_net,MusicUtils.getInstance().getName());
        //播放或者暂停的按钮变化----默认打开时是暂停的图标  两种情况  1：切歌  默认暂停  2.点击图片  根据实际情况变化
        if(type==1){
            remoteViews.setImageViewResource(R.id.pOrp_net,R.drawable.baseline_pause_circle_outline_24);
        }else{
            if(MusicUtils.getInstance().isPlay()){
                remoteViews.setImageViewResource(R.id.pOrp_net,R.drawable.baseline_pause_circle_outline_24);
            }else{
                remoteViews.setImageViewResource(R.id.pOrp_net,R.drawable.baseline_play_circle_outline_24);
            }
        }
        {
            //上一首图片的点击事件
            Intent intent = new Intent("com.bw.pre");
            PendingIntent broadcast = PendingIntent.getBroadcast(getActivity(), 102, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.pre_net,broadcast);
        }
        {
            Intent intent = new Intent("com.bw.pOrp");
            PendingIntent broadcast = PendingIntent.getBroadcast(getActivity(), 103, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.pOrp_net,broadcast);
        }
        {
            Intent intent = new Intent("com.bw.next");
            PendingIntent broadcast = PendingIntent.getBroadcast(getActivity(), 104, intent, PendingIntent.FLAG_UPDATE_CURRENT);
            remoteViews.setOnClickPendingIntent(R.id.next_net,broadcast);
        }
        Intent intent = new Intent(getActivity(), MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(getActivity(), 101, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        Notification.Builder build = new Notification.Builder(getActivity())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setCustomContentView(remoteViews)
                .setContentIntent(pendingIntent);
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            manager.createNotificationChannel(new NotificationChannel("id","name",NotificationManager.IMPORTANCE_DEFAULT));
            build.setChannelId("id");
        }
        Notification notification = build.build();
        manager.notify(1,notification);
        NotificationTarget target = new NotificationTarget(getActivity(), R.id.iv_net, remoteViews, notification, 1);
        Glide.with(getContext())
                .asBitmap()
                .load(MusicUtils.getInstance().getPicUrl())
                .into(target);

    }

    private void initView(View inflate) {
        et = (EditText) inflate.findViewById(R.id.et);
        lvNet = (ListView) inflate.findViewById(R.id.lv_net);
        ivNet = (ImageView) inflate.findViewById(R.id.iv_net);
        nameNet = (TextView) inflate.findViewById(R.id.name_net);
        preNet = (ImageView) inflate.findViewById(R.id.pre_net);
        pOrpNet = (ImageView) inflate.findViewById(R.id.pOrp_net);
        nextNet = (ImageView) inflate.findViewById(R.id.next_net);
    }

    class MyTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {
            return HttpUtils.getInstance().doget(strings[0]);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            List<Music.DataBean> data = new Gson().fromJson(s, Music.class).getData();
            MusicUtils.getInstance().setList(data);
            list.clear();
            list.addAll(data);
            musicAdapter.notifyDataSetChanged();
        }
    }

    class MyReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            if("com.bw.pre".equals(intent.getAction())){
                Log.d("sss", "onReceive: 111111");
                MusicUtils.getInstance().pre();
                sendNoti(1);
                change();
            }else if("com.bw.pOrp".equals(intent.getAction())){
                MusicUtils.getInstance().pOrp(pOrpNet);
                sendNoti(2);
            }else if("com.bw.next".equals(intent.getAction())){
                MusicUtils.getInstance().next();
                sendNoti(1);
                change();
            }else if("com.bw.pre.main2".equals(intent.getAction())){
                Log.d("sss", "onReceive: 111111");
                sendNoti(1);
                change();
            }else if("com.bw.pOrp.main2".equals(intent.getAction())){
                if(MusicUtils.getInstance().isPlay()){
                    pOrpNet.setImageResource(R.drawable.baseline_pause_circle_outline_24);
                }else{
                    pOrpNet.setImageResource(R.drawable.baseline_play_circle_outline_24);
                }
                sendNoti(2);
            }else if("com.bw.next.main2".equals(intent.getAction())){
                sendNoti(1);
                change();
            }
        }
    }
}